<template>
    <Form
            ref="form"
            :loading="initDataLoading"
            label-position="top"
            :form-items="formItems"
    ></Form>
</template>

<script>
    // 关联/外置表单只支持可编辑的字段
    import Form from '../../../../common-util/src/components/page/Form.vue'

    let taskSaveDataButtonCode = 'taskSaveDataButtonCode'
    let taskCompleteButtonCode = 'taskCompleteButtonCode'
    let startWorkflowButtonCode = 'startWorkflowButtonCode'
    export default {
        components:{
            Form
        },
        name: "FormRelation",
        computed:{
            formItems(){
                let r = []
                if(this.data){
                    // 表单属性
                    this.data.forEach(item=>{
                        r.push({
                            field: {
                                name: item.id,
                                value: item.value
                            },
                            element:this.itemElement(item)
                        })
                    })
                    if(!this.relationQuery.isStartForm){

                        // 审批意见
                        r.push({
                            field:{
                                name: 'comment',
                                value: '同意'
                            },
                            element:{
                                type: 'textarea',
                                label: '审批意见',
                                required: true
                            }
                        })
                    }
                    // 操作按钮

                    let buttons = []
                    // 启动或完成任务
                    let submitButtonCode = ''
                    if(this.relationQuery.isStartForm){
                        submitButtonCode = startWorkflowButtonCode
                    }else{
                        submitButtonCode = taskCompleteButtonCode

                    }
                    buttons.push({
                        action: this.submitData,
                        label: '提交',
                        code: submitButtonCode
                    })
                    if(!this.relationQuery.isStartForm){
                        // 如果是任务，添加保存数据功能
                        buttons.push({
                            action: this.saveTaskData,
                            label: '保存数据',
                            code: taskSaveDataButtonCode
                        })
                    }

                    buttons.push({
                        action: 'reset',
                        label: '重置',
                        type: 'default'
                    })
                    r.push({
                        element:{
                            type: 'button',
                            button:buttons
                        }
                    })
                }
                return r
            }
        },
        data(){
            return {
                relationQuery:{
                    processDefinitionId : this.$route.query.processDefinitionId,
                    taskId: this.$route.query.taskId,
                    isStartForm: (this.$route.query.isStartForm == undefined ? (this.$route.query.taskId? false: true): this.$route.query.isStartForm)
                },
                // 存储要渲染的表单结构数据，并通过计算属性转化为表单结构
                data: null,
                initDataLoading: false

            }
        },
        mounted(){
            this.initFormData()
        },
        methods:{
            itemElement(item){
                let element = {
                    label: item.name,
                    required: item.isRequired,
                    readonly: item.isReadOnly,
                    // 不可写的禁用
                    disabled: item.isReadOnly,
                    placeholder: item.placeholder
                }
                switch (item.type) {
                    case 'text':{
                        element.type = 'text'
                        break
                    }
                    case 'password':{
                        // 密码和文件一样
                        element.type = 'text'
                        break
                    }
                    case 'multi-line-text':{
                        // 多行文本
                        element.type = 'textarea'
                        break
                    }
                    case 'integer':{
                        // 数字
                        element.type = 'inputNumber'
                        element.inputNumber={
                            min: -10000000,
                            max: 10000000
                        }
                        break
                    }
                    case 'decimal':{
                        // 小数
                        element.type = 'inputNumber'
                        element.inputNumber={
                            min: -10000000,
                            max: 10000000,
                            precision: 2,
                            step: 0.1
                        }
                        break
                    }
                    case 'boolean':{
                        element.type = 'checkBox'
                        break
                    }
                    case 'date':{
                        element.type = 'date'
                        let information = 'yyyy-MM-dd'
                        let type = element.type

                        element.date={
                            type: type,
                            format: information,
                            valueFormat: information,
                        }
                        break
                    }
                    case 'radio-buttons':{
                        // 单选
                        element.type = 'radioGroup'
                        let data = []
                        let information = item.options
                        for (let i = 0; i < information.length; i++) {
                            data.push({
                                id: information[i].id? information[i].id:information[i].name,
                                name: information[i].name
                            })
                        }
                        element.radioGroup = {
                            data : data
                        }
                        break
                    }
                    case 'dropdown':{
                        element.type = 'selectLocal'
                        let data = []
                        let information = item.options
                        for (let i = 0; i < information.length; i++) {
                            data.push({
                                id: information[i].id? information[i].id:information[i].name,
                                name: information[i].name
                            })
                        }
                        element.selectLocal = {
                            showEmpty:false,
                            data : data
                        }
                        break
                    }
                    case 'people':{
                        // 选择人
                        element.type = 'selectRemote'
                        element.selectRemote = {
                            url: this.$baseURL.base + '/base/user/list',
                            queryProp: 'nickname',
                            optionProp:{
                                value: 'id',
                                label: 'nickname'
                            },
                        }
                        break
                    }
                    case 'functional-group':{
                        //选择组,这里选择角色
                        element.type = 'selectRemote'
                        element.selectRemote = {
                            url: this.$baseURL.base + '/base/role/list'
                        }
                        break
                    }
                    case 'expression':{
                        // 表达式，暂不支持，没弄明白
                        break
                    }
                    case 'hyperlink':{
                        // 超链接

                        element.type = 'text'
                        break
                    }
                    case 'upload':{
                        // 上传
                        element.type = 'upload'
                        let isMultiple = false
                        if(item.params && item.params.multiple){
                            isMultiple = true
                        }
                        element.upload={
                            type: element.type,
                            multiple: isMultiple,
                            limit: isMultiple? null: 1,
                            listType: 'text'
                        }
                        break
                    }
                }

                return element
            },
            // 加载要渲染的动态表单
            initFormData(){
                if(!this.relationQuery.taskId && !this.relationQuery.processDefinitionId){
                    this.$message.error('参数错误,流程定义id和任务id不能同时为空')
                    return
                }

                this.initDataLoading = true
                this.axios.get(this.$baseURL.workflow + '/workflow/form/relationForm',{params: this.relationQuery})
                    .then((res)=> {
                        this.data = res.data
                    }).catch(error=>{
                    if(error.response){
                        if(error.response.status == 401){
                            return
                        }
                        this.$message.error(error.response.data.msg)
                    }else {
                        this.$message.error('网络错误或服务不可用')
                    }
                }).finally(()=>{
                    this.initDataLoading = false
                })

            },
            submitData(){
                this.doSubmit(true,(loading)=>{
                    // 这里直接调用两次，不再判断是启动流程还是完成任务，这两个按钮不会同时出现
                    this.$refs.form.setButtonLoading(taskCompleteButtonCode,loading)
                    this.$refs.form.setButtonLoading(startWorkflowButtonCode,loading)
                })
            },
            doSubmit(isComplete,buttonLoadingFunction){
                let formRef = this.$refs.form.getFormRef()
                let formData =  this.$refs.form.getFormData()

                //表单数据
                let variables = {}
                // 如果存在下拉会存在多余的数据
                for (let formDataKey in formData) {
                    let isIgnore = false
                    // comment 为审批意见
                    if(formDataKey.indexOf('__') >=0 || formDataKey == 'comment'){
                        isIgnore = true
                    }
                    //去掉不可写的字段
                    for (let i = 0; i < this.data.length; i++) {
                        if(formDataKey == this.data[i].id && this.data[i].isWritable == false){
                            isIgnore = true
                            break
                        }
                    }
                    if(isIgnore){
                        continue
                    }
                    variables[formDataKey] = formData[formDataKey]
                }
                let postData = {
                    variables: variables
                }
                let url = null
                // 如果是启动流程
                if(this.relationQuery.isStartForm){
                    url = this.$baseURL.workflow + '/workflow/process/relationForm/startWorkflowWithForm'
                    postData.processDefinitionId = this.relationQuery.processDefinitionId
                }else {
                    url = this.$baseURL.workflow + '/workflow/task/relationForm/completeTaskWithForm'
                    postData.taskId = this.relationQuery.taskId
                    postData.isComplete = isComplete
                    // 保存数据不添加审批意见
                    if(isComplete !== false){
                        postData.comment = formData.comment
                    }
                }

                let postFuntion = ()=>{
                    buttonLoadingFunction(true)
                    this.axios.post(url,postData).then(()=>{
                        if(isComplete === false){
                            this.$message.success('保存成功')
                        }else {
                            this.$message.success('提交成功')
                            // 提交成功后按钮禁用，这里也没有区分，也没有必要区分，都禁用就是了
                            this.$refs.form.setButtonDisabled(taskCompleteButtonCode,true)
                            this.$refs.form.setButtonDisabled(startWorkflowButtonCode,true)
                            this.$refs.form.setButtonDisabled(taskSaveDataButtonCode,true)
                        }


                    }).catch(error=>{
                        if(error.response){
                            if(error.response.status == 401){
                                return
                            }
                            this.$message.error(error.response.data.msg)
                        }else {
                            this.$message.error('网络错误或服务不可用')
                        }
                    }).finally(()=>{
                        buttonLoadingFunction(false)
                    })
                }
                // 保存数据不验证表单
                if(isComplete === false){
                    postFuntion()
                }else{
                    // 表单验证并提交
                    formRef.validate((valid) => {
                        if (valid) {
                            postFuntion()
                        } else {
                            this.$message.error('表单验证不通过')
                            return false;
                        }
                    });
                }

            },
            //任务办理只保存数据
            saveTaskData(){
                this.doSubmit(false,(loading)=>{
                    this.$refs.form.setButtonLoading(taskSaveDataButtonCode,loading)
                })
            }
        }
    }
</script>

<style scoped>

</style>